package handler;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;

/**
 * 创建时间：2017年12月05日18:03 <br>
 * 作者：fuchaoyang <br>
 * 描述：
 */

public abstract class IntentService extends Service {
  private String mThreadName;
  private Looper mServiceLooper;
  private ServiceHandler mServiceHandler;
  private boolean mRedelivery;

  private final class ServiceHandler extends Handler {

    public ServiceHandler(Looper looper) {
      super(looper);
    }

    @Override public void handleMessage(Message msg) {
      // 3.通过handler处理消息，完成后，stop自己
      onHandleIntent((Intent) msg.obj);
      stopSelf(msg.arg1);
    }
  }

  public void setThreadName(String threadName) {
    mThreadName = threadName;
  }

  public void setRedelivery(boolean redelivery) {
    mRedelivery = redelivery;
  }

  public void onCreate() {
    HandlerThread handlerThread = new HandlerThread(mThreadName);
    handlerThread.start();

    // 1.Use the provided {@link Looper} instead of the default one.这里创建的是Looper对应的线程的Handler
    mServiceLooper = handlerThread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
  }

  public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
    Message message = mServiceHandler.obtainMessage();
    message.obj = intent;
    message.what = startId;
    // 2.service建立连接后，通过handler发送消息处理
    mServiceHandler.sendMessage(message);
    return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
  }

  protected abstract void onHandleIntent(@Nullable Intent intent);

  @Override public void onDestroy() {
    super.onDestroy();
    mServiceLooper.quit();
  }
}
